package com.lottoad.android.activity.ad.request;

import org.w3c.dom.Element;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.telephony.PhoneNumberUtils;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.lottoad.android.R;
import com.lottoad.android.activity.info.LottoAdAdressListActivity;
import com.lottoad.android.common.BaseActivity;
import com.lottoad.android.cronos.http.CNLottoAdApiSetEx;
import com.lottoad.android.util.BKAddress;
import com.lottoad.android.util.BKLocationManager;
import com.lottoad.android.util.CNCronosLog;

public class LottoAdRequestActivity extends BaseActivity implements BKLocationManager.LocationStateListener {
	private String TAG = "LottoAdRequestActivity";
	
	private final int REQUEST_ADDRESS_ACTIVITY = 10000;
	private BKLocationManager mLocationManager;
	private TextView mAddressTextView;
	
	private Context mContext;
	
	private EditText mCompanyName, mRepresentativeName, mPhoneNumber, mAdPart;
	private Button mLocation;
	
	private Button mConfirmButton, mCancelButton;
	
	private String mSido = "", mGugun = "", mDong = "", mAddress = "";
	
	private boolean mIsAddrSelect = false;
	
	/*LottoAdAdressListActivity*/
	@Override
	protected int onGetContentViewResource() {
		// TODO Auto-generated method stub
		return R.layout.lotto_ad_request_activity;
	}
	
	@Override
	protected void onInit() {
		// TODO Auto-generated method stub
		mContext = this;
		mLocationManager = new BKLocationManager(this);
		mLocationManager.setOnLocationStateListener(this);
		
		Button locationBtn = (Button) findViewById(R.id.btn_current_location);
		locationBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mLocationManager.requestCurrentLocations();
			}
			
		});
		
		mAddressTextView = (TextView) findViewById(R.id.tv_address);
		
		mCompanyName = (EditText) findViewById(R.id.et_request_company_name);
		mRepresentativeName = (EditText) findViewById(R.id.et_request_representative_name);
		mPhoneNumber = (EditText) findViewById(R.id.et_request_phone_number);
		
//		mPhoneNumber.addTextChangedListener(new TextWatcher() {
//			@Override
//			public void afterTextChanged(Editable s) {
//			}
//
//			@Override
//			public void beforeTextChanged(CharSequence s, int start, int count,	int after) {
//			}
//
//			@Override
//			public void onTextChanged(CharSequence s, int start, int before, int count) {
//				String formattingNumber = PhoneNumberUtils.formatNumber(s.toString());
//				mPhoneNumber.setText((CharSequence) formattingNumber);
//			}
//		});
		
		mPhoneNumber.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if(event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
					showAddressListActivity();
				}
				return false;
			}
		});
		
		mLocation = (Button) findViewById(R.id.btn_request_location);
		mLocation.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showAddressListActivity();
			}
		});
		
		mAdPart = (EditText) findViewById(R.id.et_request_ad_part);
		
		mConfirmButton = (Button) findViewById(R.id.btn_request_confirm);
		mCancelButton = (Button) findViewById(R.id.btn_request_cancel);
		
		mConfirmButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				if(mCompanyName.getText().length() == 0) {
					Toast.makeText(mContext, "상호를 입력해 주세요", Toast.LENGTH_SHORT).show();
				} else if(mRepresentativeName.getText().length() == 0) {
					Toast.makeText(mContext, "대표자 성함을 입력해 주세요", Toast.LENGTH_SHORT).show();
				} else if(mPhoneNumber.getText().length() == 0) {
					Toast.makeText(mContext, "전화번호를 입력해 주세요", Toast.LENGTH_SHORT).show();
				} else if(mLocation.getText().length() == 0) {
					Toast.makeText(mContext, "지역을 입력해 주세요", Toast.LENGTH_SHORT).show();
				} else if(mAdPart.getText().length() == 0) {
					Toast.makeText(mContext, "광고 부분을 입력해 주세요", Toast.LENGTH_SHORT).show();
				} else {
					hideKeyboard();
					sendAdRequest();
				}
				
				
				
			}
		});
		
		mCancelButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				hideKeyboard();
				goBack();
				
			}
		});
		
	}
	
	private void showAddressListActivity() {
		Intent intent = new Intent(mContext, LottoAdAdressListActivity.class);
		intent.putExtra("isRegistActivity",	false);
		startActivityForResult(intent, REQUEST_ADDRESS_ACTIVITY);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if(requestCode == REQUEST_ADDRESS_ACTIVITY && resultCode == RESULT_OK){
			mIsAddrSelect = true;
			mAddress = data.getStringExtra("address");
			mSido = data.getStringExtra("sido");
			mGugun = data.getStringExtra("gugun");
			mDong = data.getStringExtra("dong");
			mLocation.setText(mAddress);
			
			mAdPart.requestFocus();
//			showKeyboard(mAdPart);
		}
		
	}
	
	public void showKeyboard(EditText which) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInputFromInputMethod(which.getApplicationWindowToken(), InputMethodManager.SHOW_IMPLICIT);
	}
	
	public void hideKeyboard() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
	}
	
	public void sendAdRequest() {
		this.onRequestData();
	}
	
	public void goBack() {
		super.onBackPressed();
	}

	@Override
	public void onAsyncPreRequest() {
		super.showLoadingDialog(R.string.requesting, mContext);
	}

	@Override
	public void onAsyncRequestCompleted(Element xmlObject) {
		super.hideLoadingDialog();
		showRequestAdSuccessDialog();
	}
	
	public void showRequestAdSuccessDialog() {
		AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
		dialog.setTitle(R.string.popup_alert).
		setMessage(R.string.request_ad_success).
		setPositiveButton(R.string.commons_ok, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				goBack();
			}
		}).show();
	}
	

	@Override
	public void onAsyncCancelRequest() {
		super.hideLoadingDialog();
		Log.e(TAG, "ASYNC CANCEL REQUEST");
	}

	@Override
	public String onGetAsyncRequestUrl() {
		String url = null;

		CNLottoAdApiSetEx MnetGlobalApiSetEx = CNLottoAdApiSetEx.getInstance();
		url = MnetGlobalApiSetEx.setRequestAdUrl(mContext, mCompanyName.getText().toString(), mRepresentativeName.getText().toString(), mPhoneNumber.getText().toString(), 
				"", mSido, mGugun, mDong, 1);
		CNCronosLog.d("onGetAsyncRequestUrl", "url : " + url);
		Log.d(TAG, "onGetAsyncRequestUrl(url : " + url);
		return url;
	}

	@Override
	public void onAsyncRequestError(int paramInt) {
		// TODO Auto-generated method stub
		super.hideLoadingDialog();
		Log.e(TAG, "REQUEST ERROR");
	}

	@Override
	public void onAsyncDataError(Element paramXMLObject, String paramString) {
		// TODO Auto-generated method stub
		super.hideLoadingDialog();
		Log.e(TAG, "ASYNC DATA ERROR");
	}

	@Override
	public void onLocationGettingtFinished(Location location, BKAddress address) {
		mAddressTextView.setText(address.getFullAddress());
		
	}

	@Override
	public void onLocationGettingError(String reason) {
		// TODO Auto-generated method stub
		
	}

	

}
